package com.pig4cloud.pig.admin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.admin.api.entity.SysHostTenant;
import com.pig4cloud.pig.admin.api.entity.SysTenant;
import com.pig4cloud.pig.admin.api.entity.SysUserTenant;
import com.pig4cloud.pig.admin.api.vo.SysTenantVo;
import com.pig4cloud.pig.admin.service.SysHostTenantService;
import com.pig4cloud.pig.admin.service.SysTenantService;
import com.pig4cloud.pig.admin.service.SysUserTenantService;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.security.tenant.TenantContextHolder;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author cx
 * @version 1.0.0
 * @ClassName SysTenantController.java
 * @createTime 2021年09月15日 15:00:00
 */
@RestController
@AllArgsConstructor
@RequestMapping({"/tenant", "/cpsRole/tenant"})
@Api(value = "tenant", tags = "租户管理模块")
@Slf4j
public class SysTenantController {

	private final SysTenantService sysTenantService;

	private final SysUserTenantService sysUserTenantService;

	private final StringRedisTemplate stringRedisTemplate;

	private final SysHostTenantService sysHostTenantService;

	/**
	 * 租户列表 - 分页
	 * @param req
	 * @return
	 */
	@RequestMapping("/page")
	public R page(SysTenantVo req){
		QueryWrapper<SysTenant> wrapper = new QueryWrapper<SysTenant>();
		String name = req.getName();
		if (StringUtils.isNotBlank(name)){
			wrapper.like("name",name);
		}
		wrapper.eq("status",0);
		wrapper.eq("del_flag",0);
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		return R.ok(sysTenantService.page(page,wrapper));
	}
	/**
	 * 租户列表
	 * @param req
	 * @return
	 */
	@Inner(value = false)
	@RequestMapping("/list")
	public R list(@RequestBody SysTenantVo req, HttpServletRequest request, HttpServletResponse response){
		if(StringUtils.isBlank(req.getUserName())){
			return R.ok(Lists.newArrayList());
		}
		//用户最新的租户ID
		String tenantId = stringRedisTemplate.opsForValue().get(CacheConstants.TELNET_LASTTIME_KEY_ + req.getUserName());
		List<SysTenant> list = sysTenantService.getList(req);
		//读取当前Host
		//String host = request.getHeader(HttpHeaders.HOST);
		String page = request.getHeader("page");


		SysHostTenant sysHostTenant = StringUtils.isBlank(page) ? null : sysHostTenantService.getOne(Wrappers.<SysHostTenant>query().lambda().eq(SysHostTenant::getHost, page).last("LIMIT 1"));
		//该域名包含的租户列表
		List<String> tenants = sysHostTenant == null ? new ArrayList<>() : (StringUtils.isBlank(sysHostTenant.getTenantId()) ? new ArrayList<>() : Arrays.asList(sysHostTenant.getTenantId().split(",")));

		log.info("当前用户的page:{}，最近的租户ID:{}，配置的可登录租户（为空代表都可登录）：{}", page, tenantId, JSON.toJSONString(tenants));
		if(CollectionUtils.isNotEmpty(list)){
			//不为空，才执行删除操作
			if(CollectionUtils.isNotEmpty(tenants)){
				//删除不包含的元素
				list.removeIf(s->(!tenants.contains(String.valueOf(s.getId()))));
			}
			//设置选中的元素
			for(SysTenant sysTenant : list){
				//tenantId为空，则不会有selected为true
				if(String.valueOf(sysTenant.getId()).equals(tenantId)){
					sysTenant.setSelected(true);
				}
			}
		}
		return R.ok(list);
	}
	/**
	 * 添加租户
	 * @param req
	 * @return
	 */
	@RequestMapping("/add")
	public R add(@RequestBody SysTenantVo req){
		if (StringUtils.isBlank(req.getName())){
			return R.failed("名称不能为空");
		}
		if (StringUtils.isBlank(req.getIndexUrl())){
			return R.failed("默认首页地址不能为空");
		}
		//check name
		List<SysTenant> sysTenantList = sysTenantService.list(Wrappers.<SysTenant>lambdaQuery().eq(SysTenant::getName,req.getName().trim()));
		if (CollectionUtils.isNotEmpty(sysTenantList)) {
			return R.failed("租户名称已经存在");
		}
		return sysTenantService.addTenant(req);
	}
	/**
	 * 当前租户信息
	 * @param req
	 * @return
	 */
	@RequestMapping("/detail")
	public R detail(@RequestBody SysTenantVo req){
		Integer tenantId = TenantContextHolder.getTenantId();
		return R.ok(sysTenantService.getById(tenantId));
	}
	/**
	 * 设置租户
	 * @param req
	 * @return
	 */
	@RequestMapping("/userSetTenant")
	public R userSetTenant(@RequestBody SysTenantVo req){
		if (StringUtils.isBlank(req.getUserId())){
			return R.failed("用户ID不能为空");
		}
		Integer tenantId = TenantContextHolder.getTenantId();
		SysUserTenant userTenant = sysUserTenantService.getOne(Wrappers.<SysUserTenant>query().lambda().eq(SysUserTenant::getUserId,req.getUserId()).eq(SysUserTenant::getTenantId,tenantId).last("LIMIT 1"));
		if (Objects.nonNull(userTenant) && userTenant.getStatus() != 1 ){
			//可能新增的用户没有选择激活
			sysUserTenantService.update(null,Wrappers.<SysUserTenant>lambdaUpdate()
					.eq(SysUserTenant::getUserId,req.getUserId())
					.eq(SysUserTenant::getTenantId,tenantId)
					.set(SysUserTenant::getStatus,1));
			return R.ok();
		}
		SysUserTenant sysUserTenant = new SysUserTenant();
		sysUserTenant.setUserId(Integer.valueOf(req.getUserId()));
		sysUserTenant.setTenantId(tenantId);
		sysUserTenant.setStatus(1);
		return R.ok(sysUserTenantService.save(sysUserTenant));
	}

	/**
	 * 取消设置租户
	 * @param req
	 * @return
	 */
	@RequestMapping("/delSetTenant")
	public R delSetTenant(@RequestBody SysTenantVo req){
		if (StringUtils.isBlank(req.getUserId())){
			return R.failed("用户ID不能为空");
		}
		String userId = req.getUserId();
		Integer tenantId = TenantContextHolder.getTenantId();
		sysUserTenantService.update(null,Wrappers.<SysUserTenant>lambdaUpdate()
				.eq(SysUserTenant::getStatus,1)
				.eq(SysUserTenant::getUserId,userId)
				.eq(SysUserTenant::getTenantId,tenantId)
				.set(SysUserTenant::getStatus,0));
		return R.ok();
	}
}
